package com.example.fw;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;


public class GroupHelper extends HelperWithWebDriverBase {

	public Groups groupCache;

	public GroupHelper(ApplicationManager manager) {
		super(manager);
	}

	public Groups getGroups() {
		if (groupCache == null) {
			buildGroupCache();
		}
		return groupCache;
	}
	
	public void buildGroupCache() {
		manager.getNavigationHelper().goToGroupsPage();
		WebElement form = findElements(By.tagName("form")).get(1);
		List<WebElement> checkboxes = form.findElements(By.name("selected[]"));
		Set<GroupObject> groups = new HashSet<GroupObject>();
		for (WebElement checkbox : checkboxes) {
			String title = checkbox.getAttribute("title");
			title = stripString(title);
			GroupObject group = new GroupObject().setName(title).setId(
					checkbox.getAttribute("value"));
			groups.add(group);
		}
		groupCache = new Groups(groups);
	}

	public GroupObject getFirstGroup() {
		WebElement checkbox = findElements(By.name("selected[]")).get(0);
		String title = checkbox.getAttribute("title");		
		title = stripString(title);	    
		GroupObject group = new GroupObject().setName(title).setId(
				checkbox.getAttribute("value"));
		return group;
	}

	public void createGroup(GroupObject validGroup) {
		manager.getNavigationHelper().goToGroupsPage();
		initGroupCreation();
		fillGroupForm(validGroup);
		submitGroup();
		manager.getNavigationHelper().returnToGroupPage();
		buildGroupCache();
	}

	private void submitGroup() {
		click(By.name("submit"));
	}

	private void fillGroupForm(GroupObject groupObject) {
		type("group_name", groupObject.name);
		type("group_header", groupObject.header);
		type("group_footer", groupObject.footer);
	}

	private void initGroupCreation() {
		click(By.name("new"));
	}

	public void editGroup(int n, GroupObject groupObject) {
		manager.getNavigationHelper().goToGroupsPage();
		selectElement("selected[]", n);
		click(By.name("edit"));
		fillGroupForm(groupObject);
		click(By.name("update"));
		manager.getNavigationHelper().returnToGroupPage();
		groupCache = null;
	}

	public void deleteGroup(int n) {
		manager.getNavigationHelper().goToGroupsPage();
		selectElement("selected[]", n);
		click(By.name("delete"));
		manager.getNavigationHelper().returnToGroupPage();
		groupCache = null;

	}
}
